<template>
<div>
    <el-dialog :title="title" :visible.sync="visible" width="500px" :before-close="handleClose">
        <el-form ref="formData" v-loading="loading"  label-width="100px">
          <!-- 
            data 绑定的渲染数据，数组
            show-checkbox 显示勾选框
            node-key 树节点的唯一标识属性名
            props 配置响应数据中对应展示的属性名
            children 是子菜单的属性名
            label 现实的菜单名
            default-checked-keys 默认勾选的集合
            default-expanded-keys 默认展开
            accordion 手风琴展开模式，会将之前展开的关闭
           -->
            <el-tree
            :data="menuList"
            show-checkbox
            node-key="id"
            accordion
            ref="tree"
            :default-checked-keys="menuIds"
            :props="{children:'children',label:'name'}">
            </el-tree>
             <el-form-item>
                    <el-button type="primary" @click="submitForm('formData')" size="mini">确定</el-button>
                    <el-button size="mini" @click="handleClose">取消</el-button>
                </el-form-item>
        </el-form>
    </el-dialog>
</div>
</template>

<script>
import menuApi from "@/api/menu"
import roleApi from "@/api/role"
  export default {
    props:{
        visible:{
            type:Boolean,
            default:false
        },
        title:{
            type:String,
            default:""
        },
        remoteClose:Function,
        roleId:null //角色id
    },
    data() {
      return {
        menuList:[], //存储所有菜单
        loading:false, //加载中 true显示加载中，false不显示加载中
        menuIds:[] //默认选中的菜单ids
      };
    },
    
    watch:{
      visible(val){
        if(val){
          //visible= true的时候加载所有菜单
          this.getMenuList()     
        }
      }
    },
    methods:{
      //获取所有菜单列表
      getMenuList(){
        //加载中
        this.loading = true
        //查询所有菜单
        menuApi.getList({}).then(res=>{
            this.menuList = res.data
            //查询角色之前所拥有的菜单ids然后进行回选
            this.getMenuIdsRoleId()
        })
        //加载完成
         this.loading = false
      },   
      //查询角色之前所拥有的菜单ids然后进行回选
      async getMenuIdsRoleId(){
        const {data} = await roleApi.getMenuIdsByRoleId(this.roleId)
        this.menuIds = data
      },  
      submitForm(formName){
        //若getCheckedKeys被选择，则返回目前呗选中的节点的node-key所组成的数组
       //1. 获取所选中节点的菜单id
        const checkedMenuIds = this.$refs.tree.getCheckedKeys()
        //2.调用保存角色菜单接口
        roleApi.saveRoleMenu(this.roleId,checkedMenuIds).then(res=>{
            if(res.code === 20000){
              this.$message({message:"分配权限成功",type:"success"})
              //关闭窗口
              this.handleClose()
            }else{
               this.$message({message:"分配权限失败",type:"error"})
            }
        })

      },
      //关闭窗口
      handleClose(){
        this.menuList = []
        this.menuIds = []
        this.remoteClose()
      },        
    }
  };
</script>

<style scoped>

</style>
